package com.zyz.forum.service.impl;

import com.zyz.forum.common.AppResult;
import com.zyz.forum.common.ResultCode;
import com.zyz.forum.dao.ArticleReplyMapper;
import com.zyz.forum.exception.ApplicationException;
import com.zyz.forum.model.ArticleReply;
import com.zyz.forum.service.IArticleReplyService;
import com.zyz.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleReplyServiceImp implements IArticleReplyService {

    @Resource
    private ArticleReplyMapper articleReplyMapper;

    @Resource
    private ArticleServiceImp articleService;

    @Override
    public void create(ArticleReply articleReply) {
        // 参数校验
        if (articleReply == null
         || articleReply.getArticleId() == null
         || articleReply.getPostUserId() == null
         || StringUtil.isEmpty(articleReply.getContent())
         ) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 构造传入信息
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        // 写入数据库
        int row = articleReplyMapper.insertSelective(articleReply);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        // 更改帖子表中的回复数
        articleService.addOneArticleReplyById(articleReply.getArticleId());
        // 新增评论成功
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        // 参数校验
        if (articleId == null || articleId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 调用dao  返回结果
        return articleReplyMapper.selectByArticleId(articleId);
    }

}
